package com.example.demo.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.entity.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import com.example.demo.utils.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yolo
 * @since 2025-03-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtUtil jwtUtil;
    @Resource
    private UserMapper userMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String register(String username, String password) {
        String token = jwtUtil.generateToken(username);
        int userId = RandomUtil.randomInt();
        User user = new User();
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        user.setUserId(userId);
        user.setUsername(username);
        if (save(user)) {
            return "注册成功！,token:" + token;
        }
        return "注册失败";
    }

    @Override
    public Result getOnlineUserList(User user) {
        User currentUser = userMapper.getUserByUsername(user.getUsername());
        List<String> onlineUserList = new ArrayList<>();
        try(Cursor<String> cursor = stringRedisTemplate.opsForSet().scan("online_users", ScanOptions.NONE)){
            while (cursor.hasNext()){
                String userId = cursor.next();
                if(!Integer.valueOf(userId).equals(currentUser.getUserId())){
                    onlineUserList.add(userMapper.getUsernameByUserId(Integer.valueOf(userId)));
                }
            }
        }
        return Result.success("操作成功！", onlineUserList);
    }
}
